package com.ants.boot.system.service.impl;

import com.ants.boot.core.exception.NotSupportFormatException;
import com.ants.boot.system.service.SysUploadService;
import com.ants.boot.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 蚂蚁会花呗
 * @date 2022/4/19 16:16
 */
@Service
public class SysUploadServiceImpl implements SysUploadService {

    private static final Logger logger = LoggerFactory.getLogger(SysUploadServiceImpl.class);

    @Value("${file.view-img-path}")
    private String viewImgPath;

    @Autowired
    FileUtils fileUtils;

    @Override
    public String uploadImg(MultipartFile file) {
        //校验文件是否图片
        if (!fileUtils.isImage(file)) {
            throw new NotSupportFormatException("不支持该格式！");
        }
        // 上传文件
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID();
        String fileUrl = null;
        try {
            fileUrl = fileUtils.upload(file, viewImgPath, fileName);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "";
        }
        return fileUrl;
    }

    @Override
    public String uploadImgBlob(MultipartFile file) {
        // 上传文件
        String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID();
        String fileUrl = null;
        try {
            fileUrl = fileUtils.upload(file, viewImgPath, fileName);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return "";
        }
        return fileUrl;
    }

    @Override
    public List<String> uploadListImg(List<MultipartFile> files) {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files){
            list.add(this.uploadImg(file));
        }
        return list;
    }
}
